package com.supor.aiot.mine.ui.login;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.inputmethod.EditorInfo;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.android.baseconfig.base.RxBus3;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.RxTimerUtil;
import com.android.baseconfig.common.utils.SystemUtils;
import com.android.baseconfig.common.utils.ToastUtils;
import com.android.baseconfig.common.utils.Util;
import com.android.baseconfig.constact.AppGlobalHost;
import com.android.baseconfig.data.http.retrofit2.exception.ApiException;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporPresenter;
import com.supor.aiot.common.arouter.PathUrl;
import com.supor.aiot.common.base.BaseMVVMActivity;
import com.supor.aiot.common.entity.Result;
import com.supor.aiot.common.entity.UserInfo;
import com.supor.aiot.common.interfaces.CustomClickListener;
import com.supor.aiot.common.ui.activity.WebActivity;
import com.supor.aiot.mine.R;
import com.supor.aiot.mine.databinding.ActivityLoginBinding;

import androidx.annotation.NonNull;

@Route(path = PathUrl.PATH_LOGIN)
public class LoginActivity extends BaseMVVMActivity<LoginViewModel, ActivityLoginBinding> {

    private boolean isCountdown;
    private String retrySend;
    //震动
    private Vibrator vibrator;

    @Override
    protected int resourceId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        super.initView();
        bindingView.toolbar.setIvLeftOnClickListener(v -> finish());
        bindingView.btnNextStep.setEnabled(false);
        // 请您阅读完整版用户服务协议以及隐私保护声明
        String tip = getString(R.string.login_privacy_text);
        SpannableString spannableString = new SpannableString(tip);
        ClickableSpan clickableSpan1 = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                gotoPrivacy(AppGlobalHost.getHost() + Constants.USERSERVERAGREE);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                ds.setUnderlineText(false);
            }
        };
        spannableString.setSpan(clickableSpan1, tip.indexOf("用户"), tip.indexOf(
                "用户") + 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ClickableSpan clickableSpan2 = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                gotoPrivacy(AppGlobalHost.getHost() + Constants.USERPRIVACYAGREE);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                ds.setUnderlineText(false);
            }
        };
        spannableString.setSpan(clickableSpan2, tip.indexOf("隐私"), tip.indexOf("隐私") + 6,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)),
                tip.indexOf("用户"), tip.indexOf("用户") + 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)),
                tip.indexOf("隐私"), tip.indexOf("隐私") + 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        bindingView.tvPrivacyTip.setText(spannableString);
        bindingView.tvPrivacyTip.setHighlightColor(0x00000000);
        bindingView.tvPrivacyTip.setMovementMethod(LinkMovementMethod.getInstance());

        retrySend = getString(R.string.retry_get_captcha);
    }

    @Override
    protected void initData() {
        super.initData();

        viewModel.getLoginResult().observe(this, loginResult -> {
            if (loginResult == null) {
                return;
            }
            // bindingView.loading.setVisibility(View.GONE);
            closeLoading();
            if (loginResult instanceof Result.Error) {
                if (loginResult.getError() instanceof ApiException) {
                    showLoginFailed(((ApiException) loginResult.getError()).getMsg());
                }
            } else if (loginResult instanceof Result.Success) {
                UserInfo userInfo = (UserInfo) loginResult.getData();
                updateUiWithUser(userInfo);
                // Intent intent = new Intent();
                // intent.putExtra(Constants.Key.USER_INFO, userInfo);
                // setResult(Activity.RESULT_OK);

                //Complete and destroy login activity once successful
                finish();
            }
        });

        viewModel.getSendCaptchaResult().observe(this, result -> {
            closeLoading();
            if (result instanceof Result.Error) {
                isCountdown = false;
                showLoginFailed(result.getError().getMessage());
            } else if (result instanceof Result.Success) {
                ToastUtils.getInstance().showCustomToast("验证码已发送");
                startTimer();
                bindingView.tvSendCaptcha.setEnabled(false);
                bindingView.tvSendCaptcha.setTextColor(getResources().getColor(R.color.content_assist));
            }
        });


        bindingView.etMobile.setLength(13);
        bindingView.etMobile.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 13 && bindingView.etCaptcha.getInputText().length() == 4) {
                    bindingView.btnNextStep.setEnabled(true);
                } else {
                    bindingView.btnNextStep.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                checkPhone(String.valueOf(s));
            }
        });
        bindingView.etCaptcha.setLength(4);
        bindingView.etCaptcha.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 4 && bindingView.etMobile.getInputText().length() == 13) {
                    bindingView.btnNextStep.setEnabled(true);
                } else {
                    bindingView.btnNextStep.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {}
        });
        bindingView.etCaptcha.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                // checkLogin();
                SystemUtils.showInputSoftFromWindowMethod(AppAgent.getApp(), bindingView.etMobile);
            }
            return false;
        });

        bindingView.clPrivacy.setOnClickListener(v -> bindingView.slideBtn.setOpen(!bindingView.slideBtn.isOpen()));
        bindingView.slideBtn.setOnSlideButtonChangeListener((view, isOpen) -> bindingView.clPrivacy.setSelected(isOpen));

        bindingView.btnNextStep.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick(View v) {
                checkLogin();
            }
        });

        bindingView.tvSendCaptcha.setOnClickListener(v -> {
            if (!Util.isMobileNO(bindingView.etMobile.getInputText())) {
                ToastUtils.getInstance().showCustomToast(getString(R.string.phone_validity));
                return;
            }
            if (!isCountdown) {
                isCountdown = true;
                showLoading();
                viewModel.sendCaptcha(bindingView.etMobile.getInputText());
            }
        });
        bindingView.etMobile.postDelayed(() -> {
            bindingView.etMobile.setFocusable(true);
            bindingView.etMobile.setFocusableInTouchMode(true);
            bindingView.etMobile.requestFocus();
            SystemUtils.showInputSoftFromWindowMethod(AppAgent.getApp(), bindingView.etMobile);
        }, 500);

        vibrator = (Vibrator) AppAgent.getApp().getSystemService(Service.VIBRATOR_SERVICE);
    }

    private void checkLogin() {
        if (!bindingView.slideBtn.isOpen()) {
            ToastUtils.getInstance().showCustomToast(getString(R.string.login_check_tip_text));
            if (vibrator == null) {
                vibrator = (Vibrator) AppAgent.getApp().getSystemService(Service.VIBRATOR_SERVICE);
            }
            vibrator.vibrate(VibrationEffect.createWaveform(new long[]{200, 200, 200, 200, 200, 200, 200},
                    -1));
            return;
        }
        if (!Util.isMobileNO(bindingView.etMobile.getInputText())) {
            ToastUtils.getInstance().showCustomToast(getString(R.string.phone_validity));
            return;
        }
        showLoading();
        SystemUtils.hideInputSoftFromWindowMethod(LoginActivity.this, bindingView.btnNextStep);
        viewModel.login(bindingView.etMobile.getInputText(),
                bindingView.etCaptcha.getInputText());
    }

    /**
     * 手机号添加空格： 135 4344 2234
     *
     * @param s
     */
    private void checkPhone(String s) {
        // Logc.e("afterTextChanged: " + s);
        StringBuilder sb = new StringBuilder(s);
        if (s.length() > 8) {
            boolean b = !" ".equalsIgnoreCase(String.valueOf(s.charAt(3)));
            if (b) {
                sb.insert(3, " ");
                bindingView.etMobile.setText(sb);
                return;
            }
            if (!" ".equalsIgnoreCase(String.valueOf(s.charAt(8)))) {
                sb.insert(8, " ");
                bindingView.etMobile.setText(sb);
                return;
            }
            String phone = sb.toString().replace(" ", "");
            if (phone.length() != sb.length() - 2) {
                Logc.e("onTextChanged: " + sb);
                sb = new StringBuilder(phone);
                sb.insert(3, " ");
                sb.insert(8, " ");
                bindingView.etMobile.setText(sb);
                return;
            }
            bindingView.etMobile.setSelection(sb.length());
        } else if (s.length() > 3) {
            boolean b = !" ".equalsIgnoreCase(String.valueOf(s.charAt(3)));
            if (b) {
                sb.insert(3, " ");
                bindingView.etMobile.setText(sb);
                return;
            }
            String phone = sb.toString().replace(" ", "");
            if (phone.length() != sb.length() - 1) {
                Logc.e("onTextChanged: " + sb);
                sb = new StringBuilder(phone);
                sb.insert(3, " ");
                bindingView.etMobile.setText(sb);
                return;
            }
            bindingView.etMobile.setSelection(sb.length());
        }
    }

    /**
     * 开始倒计时
     */
    public void startTimer() {
        RxTimerUtil.countdown(60, number -> {
            if (number >= 0) {
                bindingView.tvSendCaptcha.setText(String.format(retrySend, number));
            } else {
                isCountdown = false;
                bindingView.tvSendCaptcha.setText(R.string.get_captcha);
                bindingView.tvSendCaptcha.setEnabled(true);
                bindingView.tvSendCaptcha.setTextColor(getResources().getColor(R.color.colorPrimary));
            }
        });
    }

    /**
     * 停止倒计时
     */
    public void stopTimer() {
        RxTimerUtil.cancelCountdown();
    }

    private void updateUiWithUser(UserInfo model) {
        SuporPresenter.getInstance().saveInfo(model, true);
        RxBus3.getInstance().post(Constants.Tag.LOGIN, Constants.Value.SUCCESS);
    }

    private void gotoPrivacy(String url) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putInt(Constants.Key.param_type, 1);
        bundle.putString(Constants.Key.param_url, url);
        intent.putExtras(bundle);
        intent.setClass(LoginActivity.this, WebActivity.class);
        startActivity(intent);
    }

    private void showLoginFailed(String errorString) {
        ToastUtils.getInstance().showCustomToast(errorString);
    }

    @Override
    public void finish() {
        SystemUtils.hideInputSoftFromWindowMethod(AppAgent.getApp(), bindingView.etMobile);
        super.finish();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopTimer();
    }
}